<template>
  <view class="content">
    <!-- title -->
    <header-modal></header-modal>

    <!-- 设置密码 -->
    <view class="rule fz30">
      <view class="tit flex flex-x-between main-theme-bgcolor fff">
        <view>收费规则</view>
        <view v-if="state.midwayPickTimes > 0">
          <sw-icons color="#fff" icon="icon-liebiaoxunhuan" class="mr10"></sw-icons>
          可中途开门{{ state.midwayPickTimes }}次
        </view>
        <view v-else>
          <sw-icons color="#fff" icon="icon-danquxunhuan" class="mr10"></sw-icons>
          不可中途开门
        </view>
      </view>
      <view class="ct bg-white">
        <template v-for="(item, index) in state.setmeals" :key="index">
          <template v-if="state.cellType === item.cellType.toString()">
            <view class="li flex" v-for="(item2, index2) in item.apkRemark.split('@')" :key="`key${index2}`">
              <view class="flex1">{{ item2 }}</view>
            </view>
          </template>
        </template>
      </view>
    </view>

    <!-- 柜门 -->
    <view class="cell bg-white">
      <view class="tit">请选择柜门</view>
      <view class="ct t-c">
        <view class="orange fz80 scale-in-out">{{ state.cellNum }}</view>
        <view class="btn-edit gray6" @click="proxy.$jump.navigateTo(`/pages/deposit/cellselect?cellType=${state.cellType}&cellNum=${state.cellNum}`)">修改></view>
        <view class="recommend">推荐</view>
      </view>
    </view>

    <!-- 支付 -->
    <view class="btn-box mt40">
      <button class="btn main-theme-bgcolor fff" form-type="submit" :disabled="false" @click="popupShow(popupRef, true)">支付开门</button>

      <checkbox-group name="checkbox" class="mt40" @change="checkboxChange">
        <label>
          <checkbox value="1" :checked="true" />
          <text class="main-theme-color" @click.stop="popupShow(popupAgreenmentRef)">《快存柜用户协议》</text>
        </label>
      </checkbox-group>
    </view>

    <!-- 支付弹窗 -->
    <uni-popup ref="popupRef" type="bottom">
      <view class="popup popup-pay bg-white">
        <sw-icons class="popup-close" @click="popupClose(popupRef)" color="#ccc" size="40" icon="icon-guanbi"></sw-icons>
        <view class="tit fz36 flex flex-y-center">
          <sw-icons type="symbol" size="40" icon="icon-pingmu" class="mr10"></sw-icons>
          找准柜门，请勿存错！
        </view>
        <view class="ct">
          <view class="num t-c fz80 red">
            {{ state.cellNum }}
            <text class="fz28">号</text>
          </view>
          <view class="item flex mt40 fz32 flex-x-between">
            <view>支付</view>
            <view>{{ state.totalFee }}元</view>
          </view>
        </view>
        <view class="btn-box mt50 flex t-c fz34">
          <button class="flex1 main-theme-bgcolor fff" :disabled="state.btnDisabled" @click="payOrder">
            确认支付
            <text class="fz28 red">（￥{{ state.totalFee }}）</text>
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 协议弹窗 -->
    <uni-popup ref="popupAgreenmentRef" type="center">
      <view class="popup popup-agreenment bg-white">
        <sw-icons class="popup-close" @click="popupClose(popupAgreenmentRef)" color="#ccc" size="40" icon="icon-guanbi"></sw-icons>
        <view class="tit fz36 t-c">快存柜用户协议</view>
        <view class="ct fz30 t-j"><agreement-modal></agreement-modal></view>
        <view class="btn-box mt20 flex t-c fz34"><view class="flex1 main-theme-bgcolor fff" @click="popupClose(popupAgreenmentRef)">确认</view></view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import agreementModal from '@/components/agreement/index.vue';
import HeaderModal from '@/components/header/index.vue';
import { ref, reactive, getCurrentInstance } from 'vue';
import { makePayOrder, queryByMainBoardId, queryOrderPayAmount } from '@/common/js/getData.js';
import { onLoad } from '@dcloudio/uni-app';

const { proxy } = getCurrentInstance();

const popupRef = ref(null);
const popupAgreenmentRef = ref(null);

const state = reactive({
  isSend: false,
  form: {
    agreement: '1'
  },
  setmeals: [],
  cellType: '',
  cellNum: '',
  machineCellId: '',
  btnDisabled: false,
  totalFee: '0',
  midwayPickTimes: ''
});

// 页面加载完成
onLoad(async option => {
  await proxy.$onLaunched;
  state.cellType = option.cellType;
  state.cellNum = option.cellNum;
  state.machineCellId = option.machineCellId;
  loadData();
});

// 获取数据
const loadData = () => {
  const data = {
    mainboardId: getApp().globalData.mainboardId,
    cellType: state.cellType
  };
  queryByMainBoardId(data)
    .then(res => {
      const { result } = res;
      state.setmeals = result.setmeals;
      state.midwayPickTimes = result.midwayPickTimes;
      // 路由没有柜门则选用用推荐
      if (!state.cellNum) {
        const arr1 = result.availableCellList.filter(item => {
          return item.cellType.toString() === state.cellType;
        });
        state.cellNum = arr1[0].recommendCellNum;
        state.machineCellId = arr1[0].recommendCellId;
      }
      // 设置价格
      const arr2 = result.setmeals.filter(item => {
        return item.cellType.toString() === state.cellType;
      });
    })
    .catch(res => {
      uni.showToast({
        icon: 'none',
        title: '网络错误，请稍候再试'
      });
    });
};

// 展示弹窗
const popupShow = (name, bool) => {
  if (state.isSend) {
    return;
  }
  if (bool) {
    if (!state.form.agreement) {
      uni.showToast({
        icon: 'none',
        title: '请同意用户协议'
      });
      return;
    }

    state.isSend = true;
    const data = {
      machineCellId: state.machineCellId
    };
    queryOrderPayAmount(data)
      .then(res => {
        state.totalFee = res.message;
      })
      .finally(() => {
        state.isSend = false;
      });
  }
  name.open();
};

// 关闭弹窗
const popupClose = name => {
  name.close();
};

// 支付成功
const onSure = () => {
  popupRef.value.close();
  proxy.$jump.navigateTo(`/pages/deposit/suc?totalFee=${state.totalFee}`);
};

// 支付
const payOrder = () => {
  state.btnDisabled = true;
  uni.getStorage({
    key: 'storageMobile',
    success(res) {
      const data = {
        ...res.data,
        totalFee: state.totalFee,
        machineCellId: state.machineCellId
      };
      makePayOrder(data)
        .then(res => {
          if (state.totalFee === '0.00') {
            state.btnDisabled = false;
            onSure();
          } else {
            wxPay(res.result);
          }
        })
        .catch(res => {
          uni.showModal({
            title: '提示',
            content: res.message,
            showCancel: false,
            success(res2) {
              if (res2.confirm) {
                state.btnDisabled = false;
                proxy.$jump.redirectTo(`/pages/deposit/cellpay?cellType=${state.cellType}`);
              }
            }
          });
        });
    },
    fail() {
      state.btnDisabled = false;
    }
  });
};

// 微信支付
const wxPay = orderInfo => {
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: orderInfo.appId, //公众号名称，由商户传入
      timeStamp: orderInfo.timeStamp.toString(), //时间戳，自1970年以来的秒数
      nonceStr: orderInfo.nonceStr, //随机串
      package: orderInfo.package,
      signType: orderInfo.signType, //微信签名方式:
      paySign: orderInfo.sign //微信签名
    },
    function(res) {
      state.btnDisabled = false;
      // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
        onSure();
      } else {
        popupRef.value.close();
        uni.showToast({
          icon: 'none',
          title: '支付失败'
        });
      }
    }
  );
};

// checkbox改变
const checkboxChange = e => {
  state.form.agreement = e.detail.value.join(',');
};
</script>

<style lang="less" scoed>
@import url('@/common/less/common.less');

.rule {
  position: relative;
  z-index: 5;
  padding: 20rpx 20rpx 0;

  &:before {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 15rpx;
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    background: #f8f8f8;
  }

  &:after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    right: 15rpx;
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    background: #f8f8f8;
  }

  .tit {
    line-height: 75rpx;
    padding: 0 20rpx;
  }

  .ct {
    padding: 30rpx 20rpx;
    line-height: 55rpx;

    .li {
      &:before {
        content: '';
        display: block;
        width: 20rpx;
        height: 20rpx;
        margin: 16rpx 15rpx 0 0;
        border-radius: 50%;
        background: #ccc;
      }
    }
  }
}

.cell {
  overflow: hidden;
  position: relative;
  padding: 30rpx 20rpx 60rpx;
  margin: 0 20rpx;
  border-top: 2rpx solid #eee;

  .ct {
    .btn-edit {
      position: absolute;
      bottom: 80rpx;
      right: 30rpx;
      font-size: 28rpx;
    }

    .recommend {
      position: absolute;
      top: -15rpx;
      right: -60rpx;
      width: 150rpx;
      height: 70rpx;
      line-height: 100rpx;
      text-align: center;
      background: @main-theme-color;
      color: #fff;
      transform: rotate(45deg);
      font-size: 24rpx;
    }
  }
}

.btn-box {
  padding: 0 20rpx;
}

.btn[disabled]:not([type]) {
  color: #fff;
  background: rgba(@yellow, 0.5);
}

.popup-pay {
  width: 100%;

  .tit {
    padding: 0 20rpx;
    line-height: 100rpx;
    border-bottom: 2px solid @line;
  }

  .ct {
    padding: 0 20rpx;

    .num {
      padding: 40rpx 0;
    }
  }

  .btn-box {
    padding: 0;
    line-height: 128rpx;
  }
}

.popup-agreenment {
  .tit {
    padding: 0 20rpx;
    border-bottom: 2px solid @line;
  }

  .ct {
    padding: 30rpx;
    line-height: 1.8;
    max-height: calc(100vh - 500rpx);
    overflow-y: auto;
    color: #666;
  }

  .btn-box {
    padding: 0;
  }
}
</style>
